<!-- MyItem -->
<template>
  <div>
    <li v-for="todo in todos" :key="todo.id">
      <el-input 
        v-model="input" 
        :placeholder="todo.title" 
        v-show="todo.isEdit" 
        @keyup.enter.native="update(todo.id)" 
        @blur="handelBlur(todo)"
        :ref="'editInput' + todo.id"
      ></el-input>
      <el-checkbox 
        :value="todo.done" 
        @change="handelCheck(todo.id)" 
        v-show="!todo.isEdit"
      >{{ todo.title }}</el-checkbox>
      <div style="display: flex">
        <el-button type="primary" size="small" @click="edit(todo)" v-show="!todo.isEdit">编辑</el-button>
        <el-button type="success" size="small" @click="update(todo.id)" v-show="todo.isEdit">完成</el-button>
        <el-button type="danger" size="small" @click="delTodo(todo.id)">删除</el-button>
      </div>
    </li>
  </div>
</template>

<script>
export default {
  name: 'MyItem',
  props: ['todos'],
  data(){
    return {
      input: '',
      checked: true
    }
  },
  methods: {
    /**
     * 删除 todo
     */
    delTodo(todoId){
      // console.log(todoId)
      this.$bus.$emit('delTodoByTodoId', todoId)
    },

    /**
     * 改变选中状态后触发的方法
     */
    handelCheck(todoId) {
      this.$bus.$emit('switchDoneByTodoId', todoId)
    },

    /**
     * 编辑
     */
    edit(todo) {
      this.input = todo.title
      this.$nextTick(() => {
        this.$refs[('editInput' + todo.id)][0].focus(); // 触发 input 元素的 focus 方法
      });
      // 通知父组件中对应的 todo.edit 变为true
      this.$bus.$emit('switchEditByTodoId', todo.id)
    },

    /**
     * 修改
     */
    update(todoId) {
      // 校验数据
      if(!this.input.trim()) return alert('输入不能为空')
      let title = this.input
      this.$bus.$emit('updateTitleByTodoId', {todoId, title})
      // 清空输入
      this.input = ''
    },

    /**
     * input 失去焦点时触发
     * 修改 isEdit 的状态，防止将 isEdit = true 进行持久化
     */
    handelBlur(todo){
      if(!this.input.trim()) return this.$set(todo, 'isEdit', false) 
      this.update(todo.id)
      // this.$set(todo, 'isEdit', false)
    }
  }
}
</script>

<style scoped>
  li {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border: 1px solid rgb(225, 225, 225);
    border-top: 0px;
    height: 35px;
  }

  li:nth-child(1) {
    border-top: 1px solid rgb(225, 225, 225);
  }
  
  li .el-input {
    width: 300px;
  }

  li .el-checkbox{
    display: flex;
    justify-content: center; 
    align-items: center; 
  }

  li:hover{
    background: rgb(243, 243, 243);
  }

  li button{
    display: none;
  }

  li:hover button{
    display: block;
  }
</style>